/*
 * ComandoSQL.java
 *
 * Created on 01/06/2011, 10:17:00
 */
package br.com.nextsql;

import br.com.nextsql.dao.DbConnection;
import br.com.nextsql.dao.DriverConexao;
import br.com.nextsql.renderizar.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class ComandoSQL extends javax.swing.JInternalFrame {
    private Connection con = null;
    private Properties principal;
    private Properties propriedades;
    private Properties comandosBasicos = new Properties();
    private CampoTexto txtLog;
    private CampoTexto txtQuery;
    public Properties getPropriedades() {
        return propriedades;
    }
    public void setPropriedades(Properties propriedades) {
        this.propriedades = propriedades;
    }
    /** Creates new form ComandoSQL */
    public ComandoSQL() {
        initComponents();
        
    }
    private void conexao() throws MalformedURLException{
        File file = new File(principal.getProperty("file.driverDir")+comandosBasicos.getProperty("Arquivo"));
        try {
            URLClassLoader ucl = new URLClassLoader(new URL[]{file.toURL()});
            Driver d = (Driver)Class.forName(comandosBasicos.getProperty("Classe"), true, ucl).newInstance();
            DriverManager.registerDriver(new DriverConexao(d));
            try{
                System.out.println(GlobalConf.descriptografar(propriedades.getProperty("Porta")));
                con = DriverManager.getConnection(comandosBasicos.getProperty("Conexao")+GlobalConf.descriptografar(propriedades.getProperty("Servidor"))+":"+GlobalConf.descriptografar(propriedades.getProperty("Porta"))+"/?", GlobalConf.descriptografar(propriedades.getProperty("Usuario")), GlobalConf.descriptografar(propriedades.getProperty("Senha")));
                Statement stm = con.createStatement();
                ResultSet rs = stm.executeQuery(comandosBasicos.getProperty("ListarBD"));
                //txtLog.setText(comandosBasicos.getProperty("ListarBD"));
                ResultSetMetaData rsmd = rs.getMetaData();
                int numColunas = rsmd.getColumnCount();
                for (int i=1; i<numColunas+1; i++) {
                    String columnName = rsmd.getColumnName(i);
                    System.out.println(columnName);
                    System.out.println(rsmd.getColumnTypeName(i));
                    //System.out.println(tableName);
                }
                System.out.println(" - ----------------- - \r\n\r\n");
                while(rs.next()){
                    System.out.println(rs.getString("datname"));
                }
            }catch(Exception ex){
                JOptionPane.showMessageDialog(null, ex);
                this.dispose();
            }
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, ex);
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jProgressBar1 = new javax.swing.JProgressBar();
        div01 = new javax.swing.JSplitPane();
        div011 = new javax.swing.JSplitPane();
        jToolBar1 = new javax.swing.JToolBar();
        btExecutar = new javax.swing.JButton();
        div0111 = new javax.swing.JSplitPane();
        divBD = new javax.swing.JScrollPane();
        BD = new javax.swing.JTree();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        div01111 = new javax.swing.JSplitPane();
        divQuery = new javax.swing.JScrollPane();
        divTabela = new javax.swing.JScrollPane();
        tabelaQuery = new javax.swing.JTable();
        divLog = new javax.swing.JScrollPane();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(415, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        div01.setDividerSize(2);
        div01.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        div01.setResizeWeight(0.9);
        div01.setPreferredSize(new java.awt.Dimension(424, 180));

        div011.setDividerLocation(22);
        div011.setDividerSize(1);
        div011.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jToolBar1.setRollover(true);

        btExecutar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/nextsql/resources/icons/artsbuilderexecute.png"))); // NOI18N
        btExecutar.setText("Executar");
        btExecutar.setFocusable(false);
        btExecutar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btExecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExecutarActionPerformed(evt);
            }
        });
        jToolBar1.add(btExecutar);

        div011.setTopComponent(jToolBar1);

        div0111.setDividerLocation(200);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("JTree");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("colors");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("sports");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("food");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("hot dogs");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("pizza");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("ravioli");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("bananas");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        BD.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        divBD.setViewportView(BD);

        div0111.setLeftComponent(divBD);

        div01111.setDividerLocation(100);
        div01111.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        div01111.setLeftComponent(divQuery);

        divTabela.setAutoscrolls(true);

        tabelaQuery.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tabelaQuery.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        divTabela.setViewportView(tabelaQuery);

        div01111.setRightComponent(divTabela);

        jTabbedPane1.addTab("Query", div01111);

        div0111.setRightComponent(jTabbedPane1);
        jTabbedPane1.getAccessibleContext().setAccessibleName("Query");

        div011.setRightComponent(div0111);

        div01.setLeftComponent(div011);
        div01.setRightComponent(divLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(div01, javax.swing.GroupLayout.DEFAULT_SIZE, 571, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(div01, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        try{
            principal = GlobalConf.lerPropriedades();
            FileInputStream file = new FileInputStream(principal.getProperty("file.bancoDir")+propriedades.getProperty("Tipo"));
            comandosBasicos.load(file);
            txtLog = new CampoTexto(comandosBasicos);
            divLog.setViewportView(txtLog);
            txtQuery = new CampoTexto(comandosBasicos);
            divQuery.setViewportView(txtQuery);
            file.close();
        }catch(Exception ex){
            JOptionPane.showMessageDialog(rootPane, ex);
            setVisible(false);
        }
        try {
            conexao();
        } catch (MalformedURLException ex) {
            Logger.getLogger(ComandoSQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formInternalFrameOpened

    private void btExecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExecutarActionPerformed
        try{
            con = DriverManager.getConnection(comandosBasicos.getProperty("Conexao")+GlobalConf.descriptografar(propriedades.getProperty("Servidor"))+":"+GlobalConf.descriptografar(propriedades.getProperty("Porta"))+"/?", GlobalConf.descriptografar(propriedades.getProperty("Usuario")), GlobalConf.descriptografar(propriedades.getProperty("Senha")));
            Statement stm = con.createStatement(
   ResultSet.TYPE_SCROLL_INSENSITIVE,   
   ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = stm.executeQuery(txtQuery.getText());
            ResultSetMetaData rsmd = rs.getMetaData();
            int numColunas = rsmd.getColumnCount();
            rs.last();
            int numLinhas = rs.getRow();
            rs.beforeFirst();
            System.out.println(numLinhas);
            String colunas[] = new String[numColunas];
            
            for (int i=1; i<numColunas+1; i++) {
                String columnName = rsmd.getColumnName(i);
                System.out.println(columnName);
                System.out.println(rsmd.getColumnTypeName(i));
                colunas[i-1] = columnName;
                //System.out.println(tableName);
            }
            System.out.println(" - ----------------- - ");
            Object linhas[][] = new Object[numLinhas][numColunas];
            int l = 0;
            while (rs.next()) {
                for (int c=0; c<numColunas; c++) {
                    System.out.println(rs.getString(c+1));
                    linhas[l][c] = rs.getString(c+1);
                }
                l++;
            }
            DefaultTableModel modelo = new DefaultTableModel(linhas, colunas);
            tabelaQuery.setModel(modelo);
             System.out.println(" - ------FIM-------- - \r\n\r\n\r\n");
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, ex);
        }
    }//GEN-LAST:event_btExecutarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTree BD;
    private javax.swing.JButton btExecutar;
    private javax.swing.JSplitPane div01;
    private javax.swing.JSplitPane div011;
    private javax.swing.JSplitPane div0111;
    private javax.swing.JSplitPane div01111;
    private javax.swing.JScrollPane divBD;
    private javax.swing.JScrollPane divLog;
    private javax.swing.JScrollPane divQuery;
    private javax.swing.JScrollPane divTabela;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tabelaQuery;
    // End of variables declaration//GEN-END:variables
}
